import { CommonField } from "@/pages/OrderModule/common/components/CommonForm";
import { Button, Col, Form, Row, Popconfirm, Image, Space, message, InputNumber, Radio, Tabs, Collapse, Steps } from "antd";
import { useState, useEffect, useRef, useCallback } from "react";
import { Input, Select, CommonInput, CommonInputNumber } from "@/views/components/PrefixPlaceholder";
import { NumText } from "@/pages/OrderModule/common/components/CommonText";
import { CommonTable } from "@/pages/OrderModule/common/components/CommonTable";
import { combinationSingleSubmit } from "../service";
import { SPU_STATUS, YES_NO_NUM_STATUS } from "@/views/utils/constant";
import { CommonModal } from "@/views/components/CommonModal";
import GoodsListModal from "./GoodsListModal";
import { useLocation, useNavigate } from "react-router-dom";
import { useArchorList } from "./archorList";
import CommonImgsLoad from "@/components/CommonImgsLoad";
import Style from "./index.module.less";
import { DoubleLeftOutlined, RightOutlined } from "@ant-design/icons";
import { useAnchor } from "@/pages/OrderModule/common/hooks/useAnchor";
import { cloneDeep, set } from "lodash";
const { Step } = Steps;
const ARCHOR_LIST_MAP = {
	basicInformation: 0, // 基础信息
	attributes: 1, // 商品属性
	otherSettings: 2 // 其他设置
};
const BatchModifyProducts = ({ handleOk }) => {
	const [visible, setVisible] = useState(0);
	const [skuList, setSkuList] = useState([]);
	const [status, setStatus] = useState(0);
	const [goodsList, setGoodsList] = useState([]);
	const [typeComb, setTypeComb] = useState("");
	const [totalCostPrice, setCostPrice] = useState(0);
	const [totalRetailPrice, setRetailPrice] = useState(0);
	const [totalPurchasePrice, setPurchasePrice] = useState(0);
	const [totalWeight, setWeight] = useState(0);
	const [infoData, setInfoData] = useState(null);
	const [records, setRecords] = useState(null);
	const [selectName, setSelectName] = useState("");
	const [lostValue, setLostValue] = useState(1);
	const [list, setList] = useState([]);
	const [deltionModal, setDeltionModal] = useState(false);
	const location = useLocation();
	const navigate = useNavigate();

	const [form] = Form.useForm();
	const goodsImage = infoData?.image;
	useEffect(() => {
		if (infoData) {
			form.setFieldsValue(infoData);
			setGoodsList(infoData.sonGoods);
			computed(infoData.sonGoods);
		} else {
			form.resetFields();
		}
	}, [infoData]);

	const CheckGoodsModalProps = {
		visible,
		selectName,
		isNotShow: true,
		handleOk() {},
		handleCancel() {
			setVisible(0);
		}
	};
	const columns = [
		{
			title: "图片",
			dataIndex: "image",
			render: (value, record, i) => <Image width={60} src={value} />
		},
		{
			title: "商品名称",
			dataIndex: "skuName"
		},
		{
			title: "颜色规格",
			dataIndex: "specs"
		},
		{
			title: "商品编码",
			dataIndex: "skuCode"
		},
		{
			title: "零售价(元)",
			dataIndex: "retailPrice",
			render: value => value && <NumText as="s1" pre="¥" num={value} />
		},
		{
			title: "成本价(元)",
			dataIndex: "costPrice",
			render: value => value && <NumText as="s1" pre="¥" num={value} />
		},
		{
			title: "市场价(元)",
			dataIndex: "tagPrice",
			render: value => value && <NumText as="s1" pre="¥" num={value} />
		},
		{
			title: "采购价(元)",
			dataIndex: "purchasePrice",
			render: value => value && <NumText as="s1" pre="¥" num={value} />
		},
		{
			title: "重量(kg)",
			dataIndex: "weight",
			render: value => value && <NumText as="s1" suffix="kg" num={value} />
		},
		{
			title: "数量(个)",
			dataIndex: "num",
			render: (text, record, index) => {
				return (
					<InputNumber min={1} precision={0} value={text ? text : 1} onChange={e => handleNumChange(e, record, index, "price")} />
				);
			}
		},
		{
			title: "商品成分",
			dataIndex: "productIngredients"
		},
		{
			title: "自定义属性",
			dataIndex: "customAttribute"
		},
		{
			title: "操作",
			dataIndex: "index",
			lock: true,
			render: (t, r, i) => (
				<span className="opera-span-common">
					<Popconfirm title="确定删除该条数据?" onConfirm={() => confirm(r, i)} onCancel={cancel}>
						<a href="#" disabled={r.isDefault == 0}>
							删除
						</a>
					</Popconfirm>
				</span>
			),
			width: 100
		}
	];
	const columns1 = [
		{
			title: "系统商品编码",
			dataIndex: "skuCode",
			render: (t, r, i) => {
				return <Input defaultValue={r.skuCode} onBlur={e => handleChange(e.target.value, r, i, 1)} orgin />;
			},
			width: 100
		},
		{
			title: "数量",
			dataIndex: "num",
			width: 100,
			render: (t, r, i) => {
				return <InputNumber defaultValue={r.num} onBlur={e => handleChange(e.target.value, r, i, 2)} orgin />;
			}
		},
		{
			title: "删除",
			dataIndex: "splitter",
			width: 100,
			render(_, record, index) {
				return (
					<>
						<Space>
							<Popconfirm title="确定删除吗？" okText="确定" cancelText="取消" onConfirm={() => remove(record, index)}>
								<Button type="link">删除</Button>
							</Popconfirm>
						</Space>
					</>
				);
			}
		}
	];
	const changeSkuCodeNum = e => {
		let data = [];
		for (let i = 1; i <= e; i++) {
			data.push({ skuCode: null, num: null });
		}
		if (list) {
			setList([...list, ...data]);
		} else {
			setList(data);
		}
	};
	useEffect(() => {
		console.log(deltionModal, "deltionModal");
		if (deltionModal) {
			console.log(list, "list");
			setList(list);
		}
	}, [deltionModal]);
	const onSkuCodeCancel = () => {
		const filteredArray = list?.filter(item => {
			return item.skuCode !== null && item.skuCode !== undefined && item.num !== null && item.num !== undefined;
		});

		setList(filteredArray);
		setDeltionModal(false);
	};
	const handleSkuCodeOk = () => {
		if (list.length > 0) {
			const hasEmptyValues = list.some(item => !item.skuCode || !item.num || (!item.skuCode && !item.num));
			if (hasEmptyValues) {
				return message.error("系统商品编码和数量不能为空");
			}
			let str = list?.map(item => `${item.skuCode}*${item.num}（件）`).join("，");
			form.setFieldValue("deletion1", str);
		}
		setDeltionModal(false);
	};

	const handleChange = async (e, record, index, type) => {
		if (type == 1) {
			list.map((x, i) => {
				if (index === i) {
					x.skuCode = e;
				}
				return x;
			});
		} else {
			list.map((x, i) => {
				if (index === i) {
					x.num = e;
				}
				return x;
			});
		}
	};
	const remove = (record, index) => {
		const arr = cloneDeep(list);
		arr.splice(index, 1);
		setList(arr);
	};

	const handleChildValue = value => {
		value.forEach(i => {
			if (!i.num) {
				i.num = 1;
			}
		});

		const modifiedData = value.map(item => {
			const modifiedItem = { ...item };
			modifiedItem.skuId = modifiedItem.id;
			delete modifiedItem.id; // 删除原始的 id 字段
			return modifiedItem;
		});
		if (goodsList) {
			setGoodsList([...goodsList, ...modifiedData]);
		} else {
			setGoodsList(modifiedData);
		}
	};
	useEffect(() => {
		computed(goodsList);
	}, [goodsList]);
	const computed = useCallback(
		value => {
			if (value) {
				let totalPrice = 0;
				let totalCostPrice = 0;
				let totalPurchasePrice = 0;
				let totalWeight = 0;
				value.forEach(item => {
					// 将字符串类型的 num 转换为数字类型
					const num = parseInt(item.num);
					// 计算 retailPrice 乘以 num
					const totalPricePerItem = (item.retailPrice ? item.retailPrice : 0) * num;
					const totalPricePerItem1 = (item.costPrice ? item.costPrice : 0) * num;
					const totalPricePerItem2 = (item.purchasePrice ? item.purchasePrice : 0) * num;
					const totalPricePerItem3 = (item.weight ? item.weight : 0) * num;
					// 累加到总价中
					totalPrice += totalPricePerItem;
					totalCostPrice += totalPricePerItem1;
					totalPurchasePrice += totalPricePerItem2;
					totalWeight += totalPricePerItem3;
				});
				setTimeout(() => {
					if (infoData) {
						if (!infoData.retailPrice) {
							form.setFieldValue("retailPrice", !isNaN(totalPrice) ? totalPrice : 0);
						}
						if (!infoData.costPrice) {
							form.setFieldValue("costPrice", !isNaN(totalCostPrice) ? totalCostPrice : 0);
						}
					} else {
						if (!form.getFieldValue("retailPrice")) {
							form.setFieldValue("retailPrice", !isNaN(totalPrice) ? totalPrice : 0);
						}
						if (!form.getFieldValue("costPrice")) {
							form.setFieldValue("costPrice", !isNaN(totalCostPrice) ? totalCostPrice : 0);
						}
					}
					form.setFieldValue("purchasePrice", !isNaN(totalPurchasePrice) ? totalPurchasePrice : 0);
				}, 500);
				setRetailPrice(totalPrice.toFixed(2));
				setCostPrice(totalCostPrice.toFixed(2));
				setPurchasePrice(totalPurchasePrice.toFixed(2));
				setWeight(totalWeight.toFixed(3));
			}
		},
		[goodsList]
	);
	//图片上传回调手动更新表单值
	const handleUploadImg = val => {
		form.setFieldsValue({
			image: val
		});
	};

	const handleNumChange = (e, record, index) => {
		const reg = /^[1-9]\d*$/;
		const val = e;
		if (reg.test(val)) {
			const arr = cloneDeep(goodsList);
			const obj = cloneDeep(record);
			obj.num = val;
			arr.splice(index, 1, obj);
			computed(arr);
			setGoodsList(arr);
		} else {
			message.info("请输入正整数");
		}
	};

	// 锚点
	const archorList = useArchorList();
	const [tab, setTab] = useState(archorList[ARCHOR_LIST_MAP.basicInformation].key);
	const contentWrapperRef = useRef(null);
	const anchorItems = useRef({});
	const { currentAnchor, scrollToAnchor } = useAnchor(contentWrapperRef, anchorItems);
	useEffect(() => {
		if (currentAnchor) {
			setTab(currentAnchor);
		}
	}, [currentAnchor]);
	useEffect(() => {
		archorList.forEach(item => {
			anchorItems.current[item.key] = document.getElementById(item.key);
		});
	}, [location.state]);
	const confirm = (r, i) => {
		const arr = cloneDeep(goodsList);
		arr.splice(i, 1);
		setGoodsList(arr);
		message.success("删除成功");
		computed(goodsList);
	};
	useEffect(() => {
		if (location.state?.type === "update") {
			if (lostValue === 1) {
				let str = location.state.data?.deletionList?.map(item => `${item.skuCode}*${item.num}（件）`).join("，");
				setList(location.state.data.deletionList);
				form.setFieldValue("deletion1", str);
				form.setFieldValue("isDeletion", location.state.data.isDeletion || 0);
				computed(location.state.data.sonGoods);
				if (location.state.data.isDeletion == 0) {
					setLostValue(0);
				}
			} else {
				form.setFieldValue("deletie", "");
				form.setFieldValue("deletie1", "");
			}
		}
	}, [location.state]);
	useEffect(() => {
		if (location.state?.type) {
			setTypeComb(location.state?.type);
			setInfoData(location.state?.data ? location.state?.data : null);
			setRecords(location.state?.record ? location.state?.record : null);
			if (location.state?.type === "add") {
				form.resetFields();
				setGoodsList([]);
			}
		}
	}, [location.state?.type]);
	function handleOk(type) {
		form.validateFields().then(async value => {
			if (goodsList.length == 0) {
				message.error("请添加商品");
				return;
			}
			value.status = status;
			if (typeComb == "copy") {
				let arrayWithoutUnwantedField = goodsList.map(obj => {
					const { id, ...rest } = obj; // 使用解构赋值来去除 unwantedField
					return rest;
				});
				value.combinations = arrayWithoutUnwantedField;
			} else {
				value.combinations = goodsList;
			}

			if (!value.image) {
				if (infoData && infoData.image) {
					value.image = infoData.image;
				} else {
					value.image = value.combinations[0].image;
				}
			}
			if (typeComb == "update") {
				value.id = records.id;
			}
			if (value.isDeletion == 0) {
				value.deletionList = [];
			} else {
				value.deletionList = list;
			}
			const { data, success } = await combinationSingleSubmit(value);
			if (success) {
				setSkuList(data);
				if (typeComb == "add") {
					message.success("新增成功");
				} else if (typeComb == "update") {
					message.success("编辑成功");
				} else {
					message.success("复制成功");
				}
				if (type === "save") {
					form.resetFields();
					setGoodsList([]);
				} else {
					setLostValue(1);
					return navigate("/views/goods/combination", { state: { type: "request" } });
				}
			}
		});
	}

	const backFn = () => {
		setLostValue(1);
		// fetchList();
		return navigate("/views/goods/combination", { state: { type: new Date().getTime() } });
	};
	const AddHandleClick = name => {
		setSelectName(name);

		setVisible(true);
	};
	const cancel = () => {};
	return (
		<div style={{ background: "#fff", padding: 20 }}>
			<div className={Style.fs18}>
				<span className="mr10">组合商品</span>
				<RightOutlined className="mr10" />
				{typeComb == "add" && <span style={{ color: "rgba(0, 104, 255, 1)", fontWeight: 700 }}>新增单个组合商品</span>}
				{typeComb == "update" && <span style={{ color: "rgba(0, 104, 255, 1)", fontWeight: 700 }}>编辑单个组合商品</span>}
				{typeComb == "copy" && <span style={{ color: "rgba(0, 104, 255, 1)", fontWeight: 700 }}>复制单个组合商品</span>}
			</div>
			<div className={Style.archor_tab + " rule-reset"}>
				<Tabs
					activeKey={tab}
					onChange={val => {
						if (val === "gototop") {
							val = archorList[ARCHOR_LIST_MAP.basicInformation].key;
						}
						setTab(val);
						scrollToAnchor(val);
					}}
				>
					{archorList.map(item => (
						<Tabs.TabPane tab={typeComb !== "update" && item.title == "其他设置" ? "" : item.title} key={item.key}></Tabs.TabPane>
					))}
				</Tabs>
			</div>
			<div className={Style.detail_inner} ref={contentWrapperRef}>
				<Form form={form} initialValues={{ ...infoData, goodsImage } || {}}>
					<Collapse
						defaultActiveKey={Object.keys(ARCHOR_LIST_MAP)}
						ghost
						expandIcon={({ isActive }) => (
							<DoubleLeftOutlined rotate={isActive ? 270 : 90} style={{ fontSize: "16px", color: "#4E5969" }} />
						)}
						expandIconPosition="end"
						className={Style["reset-collapse"]}
					>
						<>
							<Collapse.Panel header={archorList[ARCHOR_LIST_MAP.basicInformation].render()} key="basicInformation">
								<Row gutter={[12, 6]} id="basic-data">
									<Col span={12}>
										<Form.Item name="skuName" rules={[{ required: true, message: "请输入商品名称" }]}>
											<CommonInput Component={Input} placeholder="商品名称" aria-required showCount maxLength={200} />
										</Form.Item>
									</Col>
									<Col span={6}>
										<Row>
											<Col span={22}>
												<Form.Item name="skuCode" rules={[{ required: true, message: "请输入组合编码" }]}>
													<CommonInput
														Component={Input}
														placeholder="组合编码"
														disabled={typeComb === "update" ? true : false}
														aria-required
														showCount
														maxLength={200}
													/>
												</Form.Item>
											</Col>
										</Row>
									</Col>
									<Col span={6}>
										<Form.Item name="skuAbbreviation">
											<CommonField Component={Input} placeholder="商品简称" showCount maxLength={40} />
										</Form.Item>
									</Col>
									<Col span={24}>
										{!location?.state?.data?.image && (
											<Form.Item label="组合商品图片" name="image">
												<CommonImgsLoad img={goodsImage} handleOk={handleUploadImg} upLoadText="请上传" />
											</Form.Item>
										)}
										{location?.state?.data?.image && (
											<Form.Item label="组合商品图片" valuePropName="fileList" name="image">
												<CommonImgsLoad img={location.state?.data?.image} handleOk={handleUploadImg} upLoadText="请上传" />
											</Form.Item>
										)}
									</Col>
									<Col span={6}>
										<Form.Item name="retailPrice">
											<CommonInputNumber min={0} placeholder="零售价" precision={2} controls={false} />
										</Form.Item>
									</Col>
									<Col span={6}>
										<Form.Item name="costPrice">
											<CommonInputNumber min={0} placeholder="成本价" precision={2} controls={false} />
										</Form.Item>
									</Col>
									<Col span={6}>
										<Form.Item name="purchasePrice">
											<CommonInputNumber min={0} placeholder="采购价" disabled precision={2} controls={false} />
										</Form.Item>
									</Col>
									<Col span={6}>
										<Form.Item name="virtualInventory">
											<CommonInputNumber min={0} placeholder="虚拟库存" precision={2} controls={false} />
										</Form.Item>
									</Col>
									<Col span={6}>
										<Form.Item name="price1">
											<CommonInputNumber min={0} placeholder="其他价格1" precision={2} controls={false} />
										</Form.Item>
									</Col>
									<Col span={6}>
										<Form.Item name="price2">
											<CommonInputNumber min={0} placeholder="其他价格2" precision={2} controls={false} />
										</Form.Item>
									</Col>
									<Col span={6}>
										<Form.Item name="price3">
											<CommonInputNumber min={0} placeholder="其他价格3" precision={2} controls={false} />
										</Form.Item>
									</Col>

									<Col span={6}>
										<Form.Item name="attribute1">
											<CommonField Component={Input} placeholder="其他属性1" showCount maxLength={50} />
										</Form.Item>
									</Col>
									<Col span={6}>
										<Form.Item name="attribute2">
											<CommonField Component={Input} placeholder="其他属性2" showCount maxLength={50} />
										</Form.Item>
									</Col>
									<Col span={6}>
										<Form.Item name="attribute3">
											<CommonField Component={Input} placeholder="其他属性3" showCount maxLength={50} />
										</Form.Item>
									</Col>
								</Row>
							</Collapse.Panel>
							<Collapse.Panel header={archorList[ARCHOR_LIST_MAP.attributes].render()} key="attributes">
								<Row>
									<Col span={4}>
										<Form.Item label="子商品零售总价：">
											<div style={{ color: "rgba(240, 61, 41, 1)" }}>￥{totalRetailPrice >= 0 ? totalRetailPrice : 0}</div>
										</Form.Item>
									</Col>
									<Col span={4}>
										<Form.Item label="子商品成本总价：">
											<div style={{ color: "rgba(240, 61, 41, 1)" }}>￥{totalCostPrice >= 0 ? totalCostPrice : 0}</div>
										</Form.Item>
									</Col>
									<Col span={4}>
										<Form.Item label="子商品采购总价：">
											<div style={{ color: "rgba(240, 61, 41, 1)" }}>￥{totalPurchasePrice >= 0 ? totalPurchasePrice : 0}</div>
										</Form.Item>
									</Col>
									<Col span={4}>
										<Form.Item label="子商品总重量：">
											<div style={{ color: "rgba(240, 61, 41, 1)" }}>{totalWeight >= 0 ? totalWeight : 0}kg</div>
										</Form.Item>
									</Col>
								</Row>
								<Row gutter={[12, 6]}>
									<Button type="primary" style={{ marginRight: "8px" }} onClick={() => AddHandleClick("add")}>
										新增商品
									</Button>
									<CommonTable
										rowKey="key"
										scroll={{ y: `calc(100vh - 250px)` }}
										columns={columns}
										dataSource={goodsList}
										pagination={false}
									/>
								</Row>
							</Collapse.Panel>
							{typeComb == "update" && (
								<Collapse.Panel header={archorList[ARCHOR_LIST_MAP.otherSettings].render()} key="otherSettings">
									{typeComb == "update" && (
										<Row gutter={[12, 6]}>
											<Col span={24}>
												<Form.Item label="组合装是否缺失" name="isDeletion">
													<Radio.Group defaultValue={1} onChange={e => setLostValue(e.target.value)} value={lostValue}>
														<Radio value={1}>是</Radio>
														<Radio value={0}>否</Radio>
													</Radio.Group>
												</Form.Item>
											</Col>
											{lostValue == 1 && (
												<Col span={24}>
													<Form.Item label="缺失原始编码" name="deletion1">
														<Input readOnly onClick={() => setDeltionModal(true)}></Input>
													</Form.Item>
													<Form.Item label="" name="deletie"></Form.Item>
												</Col>
											)}
										</Row>
									)}
								</Collapse.Panel>
							)}
						</>
					</Collapse>
				</Form>
			</div>
			{visible == 1 && <GoodsListModal onGoodsSkuListSelected={handleChildValue} {...CheckGoodsModalProps} />}
			<Row style={{ position: "fixed", bottom: 60, right: 80 }}>
				<Col>
					<Space>
						<Button size="middle" onClick={backFn}>
							取消
						</Button>
						{typeComb == "add" && (
							<Button
								size="middle"
								onClick={() => {
									handleOk("save");
								}}
							>
								保存并继续
							</Button>
						)}
						<Button size="middle" type="primary" onClick={handleOk}>
							{typeComb == "add" ? "创建" : "保存"}
						</Button>
					</Space>
				</Col>
			</Row>
			{deltionModal && (
				<CommonModal
					title={{ title: "缺失的系统商品编码" }}
					open={true}
					className="views-table-dialog"
					width="500px"
					okText="保存"
					onCancel={onSkuCodeCancel}
					onOk={handleSkuCodeOk}
				>
					<Form.Item name="opera1">
						<Select
							style={{ width: "80%" }}
							orgin
							placeholder="添加行"
							onChange={e => {
								changeSkuCodeNum(e);
							}}
							allowClear
						>
							<Option value={1}>添加一行</Option>
							<Option value={2}>添加二行</Option>
							<Option value={5}>添加五行</Option>
						</Select>
					</Form.Item>
					<div className="views-container">
						<CommonTable
							scroll={{ y: `calc(100vh - 250px)` }}
							style={{ width: 500 }}
							columns={columns1}
							rowKey="id"
							dataSource={list}
							pagination={false}
						/>
					</div>
				</CommonModal>
			)}
		</div>
	);
};

export default BatchModifyProducts;
